package com.zzl.study.demo.config;

import com.alibaba.cloud.ai.memory.redis.RedissonRedisChatMemoryRepository;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 对话记忆配置类
 *
 * @author: zhangzl
 * @date: 2025/9/29 15:42
 * @version: 1.0
 */
@Configuration
public class MemoryConfig {

    /**
     * Redis 主机地址
     */
    @Value("${spring.ai.memory.redis.host:127.0.0.1}")
    private String redisHost;

    /**
     * Redis 端口号
     */
    @Value("${spring.ai.memory.redis.port:6379}")
    private int redisPort;

    /**
     * Redis 密码
     */
    @Value("${spring.ai.memory.redis.password:}")
    private String redisPassword;

    /**
     * Redis 数据库索引
     */
    @Value("${spring.ai.memory.redis.database:0}")
    private int redisDatabase;

    /**
     * Redis 连接超时时间
     */
    @Value("${spring.ai.memory.redis.timeout:10000}")
    private int redisTimeout;

    /**
     * Redis 连接池大小
     */
    @Value("${spring.ai.memory.redis.max-pool-size:50}")
    private int redisMaxPoolSize;

    /**
     * 向Spring容器中注入一个基于Redis的Redisson框架对话记忆存储仓库
     *
     * @return 基于Redis的Redisson框架对话记忆存储仓库
     */
    @Bean
    public RedissonRedisChatMemoryRepository redissonRedisChatMemoryRepository() {
        return RedissonRedisChatMemoryRepository.builder()
                .redissonConfig(buildRedissonConfig())
                .build();
    }

    /**
     * 构建Redisson框架的配置信息
     *
     * @return Redisson框架的配置信息
     */
    private Config buildRedissonConfig() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + this.redisHost + ":" + this.redisPort)
                .setTimeout(this.redisTimeout)
                .setConnectionPoolSize(this.redisMaxPoolSize)
                .setDatabase(this.redisDatabase)
                .setPassword(this.redisPassword);
        return config;
    }

}
